package com.jxpanda.commons.base;

import lombok.*;
import lombok.experimental.Accessors;
import lombok.experimental.SuperBuilder;

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 配合策略模式工具使用的策略对象
 *
 * @author Panda
 */
@Data
@SuperBuilder
@NoArgsConstructor
@Accessors(chain = true)
public class Strategy {

    /**
     * 往外传递的消息
     */
    private String message;

    /**
     * 猜疑链策略
     * 像链条一样环环相扣，前一环验证成功的话，才执行下一环的逻辑，如果验证失败，则中断退出，同时返回message
     */
    @Data
    @SuperBuilder
    @NoArgsConstructor
    @EqualsAndHashCode(callSuper = true)
    public static class SuspicionChain extends Strategy {
        /**
         * 是否成功
         */
        private boolean success;
        /**
         * 断言函数
         */
        private Predicate<SuspicionChain> predicate;
    }

    public static void main(String[] args) {
        List<SuspicionChain> collect = Stream.of(SuspicionChain.builder().message("01")
                        .predicate(suspicionChain -> false)
                        .build(),
                SuspicionChain.builder()
                        .message("02")
                        .predicate(suspicionChain -> true)
                        .build(),
                SuspicionChain.builder()
                        .message("03")
                        .predicate(suspicionChain -> true)
                        .build())
                .collect(Collectors.toList());
        System.out.println(collect.stream().filter(it->it.getPredicate().test(new SuspicionChain())).findFirst().orElse(SuspicionChain.builder()
                .message("default")
                .build()).getMessage());
    }

}
